<?php
/**
 * Niushop商城系统 - 团队十年电商经验汇集巨献!
 * =========================================================
 * Copy right 2019-2029 上海牛之云网络科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: https://www.niushop.com
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
 * 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
 * =========================================================
 */

namespace app\model\system;

use app\model\BaseModel;
use think\facade\Cache;
use think\facade\Db;

/**
 * 站点管理
 * @author Administrator
 *
 */
class Site extends BaseModel
{

    /**
     * getSiteInfo 获取站点详情
     * @param $condtion
     * @param string $fields
     */
    public function getSiteInfo($condition, $fields = '*')
    {
        $res = model('site')->getInfo($condition, $fields);
        return $this->success($res);
    }

    /**
     * 获取站点插件
     * @param int $site_id
     */
    public function getSiteAddon($site_id)
    {
        $site_info = model('site')->getInfo([ [ 'site_id', '=', $site_id ] ], 'site_addon');
        $site_addon = $site_info[ 'site_addon' ] ?? '';
        $addon_condition_str = "= 'system' ";
        $addon_condition = array ();
        if (!empty($site_addon)) {
            $temp_addon_array = explode(',', $site_addon);
            foreach ($temp_addon_array as $k => $v) {
                $temp_addon_array[ $k ] = "'" . $v . "'";
            }
            $temp_str = implode(',', $temp_addon_array);
            $addon_condition_str .= " OR name in ($temp_str)";
        }

        $addon_condition[] = [ "type", "exp", Db::raw($addon_condition_str) ];
        $addon_model = new Addon();
        $result = $addon_model->getAddonList($addon_condition);
        return $result;
    }

    /**
     * getSiteShopPageList 获取站点列表
     * @param array $condition
     * @param bool $fields
     * @param $order
     * @param string $limit
     * @return array
     */
    public function getSitePageList($condition = [], $page = 1, $page_size = PAGE_LIST_ROWS, $order = 'create_time desc', $fields = '*')
    {

        $res = model('site')->pageList($condition, $fields, $order, $page, $page_size, 'a');
        if ($res[ 'count' ] > 0) {
            $time = time();
            foreach ($res[ 'list' ] as $k => $v) {

                if ($v[ 'expire_time' ] == 0) {

                    $res[ 'list' ][ $k ][ 'status' ] = '正常';

                } elseif ($v[ 'expire_time' ] > $time) {

                    $cha = $v[ 'expire_time' ] - $time;
                    $date = ceil(( $cha / 86400 ));
                    if ($date < 30) {
                        $res[ 'list' ][ $k ][ 'status' ] = '即将到期';
                    } else {
                        $res[ 'list' ][ $k ][ 'status' ] = '正常';
                    }
                } else {
                    $res[ 'list' ][ $k ][ 'status' ] = '关闭';
                }
            }
        }
        return $this->success($res);
    }

    /**
     * 添加商城
     */
    public function addSite($site_data)
    {
        //判断域名信息是否是
        if (!empty($site_data[ 'site_domain' ])) {
            //格式为https://baidu.com或者http://baidu.com
            if (!preg_match('/^http(s)?:\\/\\/.+/', $site_data[ 'site_domain' ])) {
                return $this->error(-1, '域名必须以http或者https开头');
            }
            $nohttp_domain = preg_replace('/^https?/', '', $site_data[ 'site_domain' ]);
            $domian_count = model('site')->getCount([ [ 'site_domain', '=', "{$nohttp_domain}" ] ]);
            if ($domian_count > 0) {
                return $this->error(-1, '该域名已被使用，请使用其他域名');
            }
        }
        $sys_user_info = model('sys_user')->getInfo([ [ 'sys_uid', '=', $site_data[ 'sys_uid' ] ] ], 'sys_uid, username, password, is_admin');
        if (empty($sys_user_info)) {
            model('site')->rollback();
            return $this->error(-1, '非法操作！');
        }

        $site_data[ 'site_type' ] = 'shop';
        $site_data[ 'username' ] = $sys_user_info[ 'username' ];
        $site_data[ 'create_time' ] = time();

        if ($sys_user_info[ 'is_admin' ] == 1) {

            $addon = new Addon();
            $install = $addon->getAddonList([ [ "type", "<>", "system" ] ]);
            $addon_array = array_column($install[ "data" ], 'name');

            $site_data[ 'site_addon' ] = implode(',', $addon_array);
            $site_data[ 'group_id' ] = 0;
            $site_data[ 'group_name' ] = '自营店铺套餐';
            $site_data[ 'sms_num' ] = 30;
            $cache = Cache::get("niushop_cert");
            if (!empty($cache)) {
                if ($cache[ 'site_num' ] != 0) {
                    $site_count = model("site")->getCount([ [ 'site_type', '=', 'shop' ], [ 'is_try', '=', 0 ] ]);
                    if ($site_count >= $cache[ 'site_num' ]) {
                        return $this->error(-1, "当前系统授权最大店铺数量" . $cache[ 'site_num' ] . "，请联系管理员购买");
                    }
                }

            }
        } else {
            //套餐信息
            $site_group_model = new SiteGroup();
            $site_group_info = $site_group_model->getSiteGroupInfo(
                [ [ 'group_id', '=', $site_data[ 'group_id' ] ] ],
                'group_id,group_name,addon_array,sms_num'
            );
            $site_data[ 'group_id' ] = $site_group_info[ 'data' ][ 'group_id' ];
            $site_data[ 'group_name' ] = $site_group_info[ 'data' ][ 'group_name' ];
            $site_data[ 'site_addon' ] = $site_group_info[ 'data' ][ 'addon_array' ];
            if ($site_data[ 'is_try' ] == 1) {//试用
                //查询是否开启体验
                $site_config = new SiteConfig();
                $config_info = $site_config->getOpenSiteConfig();
                $site_data[ 'sms_num' ] = $config_info[ 'data' ][ 'value' ][ 'sms_num' ];
            } else {
                $site_data[ 'sms_num' ] = $site_group_info[ 'data' ][ 'sms_num' ];
                $cache = Cache::get("niushop_cert");
                if (!empty($cache)) {
                    if ($cache[ 'site_num' ] != 0) {
                        $site_count = model("site")->getCount([ [ 'site_type', '=', 'shop' ], [ 'is_try', '=', 0 ] ]);
                        if ($site_count >= $cache[ 'site_num' ]) {
                            return $this->error(-1, "当前系统授权最大店铺数量" . $cache[ 'site_num' ] . "，请联系管理员购买");
                        }
                    }

                }
            }
        }

        model('site')->startTrans();
        try {

            //添加系统站
            $site_id = model("site")->add($site_data);
            $shop_data[ 'site_id' ] = $site_id;

            $shop_data[ 'create_time' ] = time();

            model("shop")->add($shop_data);

            // 添加店铺相册默认分组
            model("album")->add([ 'site_id' => $site_id, 'album_name' => "默认分组", 'update_time' => time(), 'is_default' => 1 ]);
            //添加系统用户组
            $group = new Group();
            $group_data = [
                'site_id' => $site_id,
                'app_module' => 'shop',
                'group_name' => '管理员组',
                'is_system' => 1,
                'menu_array' => '',
                'create_time' => time()
            ];
            $group_id = $group->addGroup($group_data)[ 'data' ];
            //添加用户
            $data_user = [
                'app_module' => 'shop',
                'is_admin' => 1,
                'site_id' => $site_id,
                'group_id' => $group_id,
                'group_name' => '管理员组',
            ];
            //添加sys_user到user
            $user_info[] = array_merge($data_user, [ 'sys_uid' => $sys_user_info[ 'sys_uid' ], 'username' => $sys_user_info[ 'username' ], 'password' => $sys_user_info[ 'password' ] ]);
            model('user')->addList($user_info);
            //同时sys_user的created_site_num增1
            model('sys_user')->setInc([ [ 'sys_uid', '=', $sys_user_info[ 'sys_uid' ] ] ], 'created_site_num');
            //执行事件
            event("AddSite", [ 'site_id' => $site_id ]);

            model("site")->commit();
            return $this->success($site_id);
        } catch (\Exception $e) {
            model("site")->rollback();
            return $this->error("", $e->getMessage());
        }
    }

    /**
     * 修改商城站点信息
     * @param $site_data
     * @param $condition
     * @return int
     */
    public function editSite($site_data, $condition)
    {
        $res = model('site')->update($site_data, $condition);
        return $this->success($res);
    }

    /**
     * 修改店铺域名
     * @param $site_domain
     * @param $site_id
     * @return array
     */
    public function changeDomian($site_domain, $site_id)
    {
        //格式为https://baidu.com或者http://baidu.com
        if (!preg_match('/^http(s)?:\\/\\/.+/', $site_domain)) {
            return $this->error(-1, '域名必须以http或者https开头');
        }
        $nohttp_domain = preg_replace('/^https?/', '', $site_domain);
        $domian_count = model('site')->getCount([ [ 'site_domain', 'LIKE', "%{$nohttp_domain}%" ], [ 'site_id', '<>', $site_id ] ]);
        if ($domian_count > 0) {
            return $this->error('-1', '该域名已被使用，请使用其他域名');
        }

        $res = model('site')->update([ 'site_domain' => $site_domain ], [ [ 'site_id', '=', $site_id ] ]);
        return $this->success($res);
    }

    /**
     * 统计站点字段
     * @param $condition
     * @param $field
     */
    public function getSiteSum($condition, $field)
    {
        $res = model('site')->getSum($condition, $field);
        return $this->success($res);
    }

    /**
     * 统计站点字段
     * @param $condition
     */
    public function getSiteCount($condition)
    {
        $res = model('site')->getCount($condition, '*');
        return $this->success($res);
    }

    /**
     * 删除订单
     * @param $site_id
     */
    public function deleteSite($condition)
    {
        model('site')->startTrans();
        try {

            $site_list = model('site')->getList($condition, 'site_id');
            //删除站点
            $res = model('site')->delete($condition);
            if ($res === false)
                return $this->error();

            foreach ($site_list as $k => $v) {
                $site_id = $v[ 'site_id' ];
                //删除站点相关配置
                $config_model = new Config();
                $config_condition = array (
                    [ 'site_id', '=', $site_id ]
                );
                $config_result = $config_model->deleteConfig($config_condition);
                if ($config_result[ 'code' ] < 0) {
                    return $config_result;
                }
                //todo 删除站点相关属性 各种业务通过实现删除站点钩子来实现(例如删除商品.商品分类 . 订单......)
                $result_list = event('SiteDelete', [ 'site_id' => $site_id ]);
                if (!empty($result_list)) {
                    foreach ($result_list as $k => $v) {
                        if (!empty($v) && $v[ 'code' ] < 0) {
                            return $v;
                        }
                    }
                }
            }

            model("site")->commit();
            return $this->success();
        } catch (\Exception $e) {
            model("site")->rollback();
            return $this->error("", $e->getMessage());
        }
    }
}